// This file is a part of ChaosDB.
// Copyright (C) 2012 ChaoJianPeng
// email:chaojianpeng@gmail.com
//
// ChaosDB is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// ChaosDB is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

/*
 * net_client.cpp
 *
 *  Created on: 2012-3-7
 *      Author: chao
 */

#include "net_client.h"
#include <zmq.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

void* requester;
void* context;

/// "tcp://localhost:5555"
void dbConnect(char* ip) {
	context = zmq_init(1);
	//连接server
	requester = zmq_socket(context, ZMQ_REQ);
	zmq_connect(requester, ip);
}

void*  dbSend(void* buff, int buffLen) {
	// 构建发送消息
	zmq_msg_t request = { 0 };
	// 申请消息的空间
	zmq_msg_init_size(&request, buffLen);
	// 填充消息
	memcpy(zmq_msg_data(&request), buff, buffLen);
	// 发送消息
	zmq_send(requester, &request, 0);
	// 清理一下啊
	zmq_msg_close(&request);
	free(buff);
	// 准备接收回复
	zmq_msg_t reply = { 0 };
	zmq_msg_init(&reply);
	// 接收回复
	zmq_recv(requester, &reply, 0);
	// 读取回复消息
	int size = zmq_msg_size(&reply);
	void *res = malloc(size);
	memset(res, 0, size);
	memcpy(res, zmq_msg_data(&reply), size);
	zmq_msg_close(&reply);
	return res;
}

void dbClose() {
	zmq_close(requester);
	zmq_term (context);
}
